<template>
  <!-- 校验地址 -->
  <div class="addressCheck">
    <div v-if="isHandling" class="isLoagin-address">
      <img :src="pathLoading" alt="沙漏" />
      <span class="loading-text1" style="margin-top: 10px">系统正在获取标准地址数据</span>
      <span class="loading-text1">请耐心等待…</span>
      <span class="loading-text2" style="margin-top: 10px">数据处理过程中，可以离开本页面。</span>
      <span class="loading-text2">数据处理完成后，再次打开本页面，会呈现处理结果。</span>
    </div>
    <div class="address-check_container" v-else>
      <!-- <div class="map" v-if="isShowMap"> -->
      <div class="map">
        <bs-com-map
          style="height:100%;"
          vid="10086"
          :zoom="zoom"
          :zooms="[3, 18]"
          :center="centerPoint"
          :editable="editable"
          @zoomend="zoomendEvent"
          @click="mapClick"
          @movestart="movestart"
        >
          <div v-for="(item, index) in points" :key="item.id">
            <template
              v-if="(item.is_sure_standard_address == '否' && ($store.state.currentBtnType == 'only' || $store.state.currentBtnType == 'more')) || $store.state.currentBtnType != 'only' && $store.state.currentBtnType != 'more'"
            >
              <template v-if="item.point[0] && item.point[1]">
                <map-marker
                  :icon="item.isCheck ? mapicon_on : mapicon"
                  :position="item.point"
                  :offset="[0, 0]"
                  :editable="false"
                ></map-marker>
                <map-text
                  id="mapText"
                  slot="reference"
                  :text="index + 1"
                  :offset="[15, 14]"
                  :position="item.point"
                  @click="(e) => markerClick(e, item)"
                ></map-text>
              </template>
            </template>
          </div>
        </bs-com-map>
      </div>

      <!-- 左侧列表 List -->
      <addrCheckingList :isShowDialogFunc="isShowDialogFunc"></addrCheckingList>

      <!-- 右侧详情 table -->
      <template
        v-if="$store.state.currentTargetAddrInfo && $store.state.currentTargetAddrInfo.target_address"
      >
        <addrCheckingDetail></addrCheckingDetail>
      </template>

      <!-- v-if="(posi_left || posi_top) && isShowDialog && pointRepeatMaps[currentPoint.id] && pointRepeatMaps[currentPoint.id].length > 1" -->
      <div
        v-if="(posi_left || posi_top) && isShowDialog && $store.state.currentBtnType !== 'nothing'"
        class="posidiv"
        id="posidiv"
        :style="`left: ${posi_left + 10}px; top: ${posi_top + 10}px`"
      >
        <template v-if="computedIsRepeat">
          <div class="p_title">
            <div>该点位上有多个重叠</div>
            <img :src="closeIcon" alt="closeIcon" @click="isShowDialog=false" />
          </div>
          <div class="p_wrapper">
            <div class="p_list">
              <template v-for="(item, index) in pointRepeatMaps[currentPoint.id]">
                <div class="p_item" :key="index" v-if="item.isShow">
                  <div class="p_left">
                    <img :src="item.isCheck ? mapicon_on : mapicon" alt="mapicon" />
                    <div>{{ index + 1 }}</div>
                  </div>
                  <div class="p_right">
                    <div class="p_name">{{ item.addr }}</div>
                    <div class="p_lg">经纬度:{{ item.point[0] }},{{ item.point[1] }}</div>
                    <el-button
                      size="mini"
                      type="primary"
                      v-if="$store.state.currentBtnType != 'sure'"
                      @click="confirmAddrClick(item)"
                    >确认此地址</el-button>
                  </div>
                </div>
              </template>
            </div>
            <div style="width:100%;text-align:center;color:#bbb;font-size:12px;margin-top:20px;">到底了</div>
          </div>
        </template>
        <template v-else>
          <div class="bzdz" v-for="item in pointRepeatMaps[currentPoint.id]" :key="item.id">
            <template v-if="item.isShow">
              <img :src="closeIcon" alt="closeIcon" class="closeicon" @click="isShowDialog=false" />
              <div class="b_title">标准地址:</div>
              <div class="b_text">{{item.addr}}</div>
              <div class="b_title" style="margin-top:15px;">经纬度:</div>
              <div class="b_text" style="margin-bottom: 10px;">{{item.point[0]}},{{item.point[1]}}</div>
              <el-button
                size="mini"
                type="primary"
                @click="confirmAddrClick(item)"
                v-if="$store.state.currentBtnType != 'sure'"
              >确认此地址</el-button>
              <!-- <el-button size="mini" type="primary" @click="confirmAddrClick(item)">确认此地址1</el-button> -->
            </template>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import pathLoading from "@/icons/noData.svg";
import addrChangeWin from "./addrCollect/addrChangeWin";
import addrEditWin from "./addrCollect/addrEditWin";
import addrHandCheckWin from "./addrCheck/addrHandCheckWin";
import addrCheckingList from "./addrCheck/addrCheckingList";
import addrCheckingDetail from "./addrCheck/addrCheckingDetail";
import mapicon from "@/icons/location.png";
import mapicon_on from "@/icons/mapicon_on.svg";

import { getDistance, addOperationLog } from "@/utils/index";

import closeIcon from "@/icons/close.svg";

export default {
  props: ["isHandling", "refresh"],
  components: {
    addrChangeWin,
    addrEditWin,
    addrHandCheckWin,
    addrCheckingList,
    addrCheckingDetail,
  },
  data() {
    return {
      closeIcon,
      mapicon,
      mapicon_on,
      pathLoading,
      editTargetAddressShowDialog: false,
      editAddressDialogShow: false,
      positioningManualWinShow: false,
      oldAddr: "",
      points: [],
      isShowDialog: false,
      // 地图相关
      editable: {
        type: "polygon", // polygon | marker
        style: {
          // 非必填
          polygon: {
            strokeStyel: "solid",
            strokeColor: "#129999",
            strokeOpacity: 1,
            strokeWeight: 1,
            fillColor: "#129999",
            fillOpacity: 0.2,
          },
        },
        isAdsorb: false, // 是否吸附
        adsorbRange: 1000, // 吸附范围，单位：像素
      },
      posi_left: 0,
      posi_top: 0,
      currentPoint: null,
      pointRepeat: [],
      isShowMap: true,
      zoom: 13,
      centerPoint: [121.511096, 31.301256],
      interval: null,
      idRepeatMaps: {},
    };
  },
  created() {},
  destroyed() {
    clearInterval(this.interval);
  },
  mounted() {
    if (this.isHandling) {
      console.log("isHandling");
      this.interval = setInterval(async () => {
        const res = await this.axios.post(this.apis.importFileRecordQuery, {
          page: 1,
          limit: 1000,
          handle_status: ["处理中", "已完成"],
        });
        if (res.retCode === 2000) {
          let item = res.rows.items.find(
            (item) => item.id == this.$store.state.currentFileInfo.id
          );
          if (
            item.handle_status == "处理中" &&
            item.api_handle_status == "已完成"
          ) {
            this.refresh();
            clearInterval(this.interval);
          }
        }
      }, 30 * 1000);
    }
    this.getPoints();
  },
  watch: {
    "$store.state.mapPoints": {
      handler: function () {
        console.log("mapPoints xx");
        this.getPoints();
      },
    },
    // "$store.state.currentFileInfo": {
    //   deep: true,
    //   handler: function (val, oldval) {
    //     this.getPoints();
    //   },
    // },
    getCurrentFileInfo: function (val, oldval) {
      console.log("currentFileInfo变化了", val, oldval);
      if (JSON.stringify(val) !== JSON.stringify(oldval)) {
        this.getPoints();
      }
    },
  },

  computed: {
    getCurrentFileInfo() {
      return this.$store.state.currentFileInfo;
    },
    computedIsRepeat: function () {
      let arr = this.pointRepeatMaps[this.currentPoint.id];
      return arr && arr.filter((item) => item.isShow).length > 1;
    },
  },

  methods: {
    isShowDialogFunc() {
      console.log("isShowDialogFunc");
      this.isShowDialog = false;

      this.zoomendEvent();
    },
    mapClick(item) {
      console.log(item.extData);
    },
    zoomendEvent(e) {
      this.posi_top = 0;
      this.posi_left = 0;
    },
    closeDialog(dialogStr) {
      this[dialogStr] = false;
    },
    editAddressShowFunc(ids) {
      this.editAddressDialogShow = true;
      console.log(ids, "ids");
    },
    markerClick(e, item) {
      console.log("yyy");
      this.isShowDialog = true;
      console.log(e, "e");
      this.points.forEach((it2) => {
        if (it2.id == item.id) {
          it2.isCheck = true;
          if (it2.isCheck) {
            this.currentPoint = it2;
          }
        } else {
          it2.isCheck = false;
        }
      });

      console.log(this.currentPoint, "currentPoint");

      console.log(item, "titem");
      this.posi_left = e.extData.originEvent.clientX;
      this.posi_top = e.extData.originEvent.clientY;
      this.$nextTick(() => {
        console.log(
          document.getElementById("posidiv"),
          'document.getElementById("posidiv")'
        );
        let divWidth = document.getElementById("posidiv").clientWidth;
        let divHeight = document.getElementById("posidiv").clientHeight;
        console.log(divWidth, "divWidth");
        console.log(divHeight, "divWidth");
        this.posi_left = e.extData.originEvent.clientX - divWidth;
        this.posi_top = e.extData.originEvent.clientY - divHeight;
      });
    },
    deleteRepactItem(dataSource) {
      let addrArr = [];
      dataSource.forEach((item) => {
        item.isShow = false;
        if (!addrArr.includes(item.addr)) {
          item.isShow = true;
          addrArr.push(item.addr);
        }
      });
      return dataSource;
    },
    getPoints() {
      this.isShowDialog = false;
      console.log(
        this.$store.state.currentBtnType,
        "this.$store.state.currentBtnType"
      );
      if (this.$store.state.currentBtnType === "nothing") {
        this.points = [];
        this.pointRepeatMaps = {};
        return;
      }
      this.points = this.$store.state.mapPoints || [];
      console.log(this.points, "this.points");
      if (this.points.length > 0) {
        this.centerPoint = this.points[0].point;
      }
      this.zoom = 10;

      let pointRepeatMaps = {};
      let idRepeatMaps = {};
      this.points.forEach((it1) => {
        let pushArr = [];
        this.points.forEach((it2, idx2) => {
          let jl = getDistance(
            it1.point[0],
            it1.point[1],
            it2.point[0],
            it2.point[1]
          );
          if (jl <= 0.6) {
            pushArr.push(it2);
          }
        });
        pointRepeatMaps[it1.id] = this.deleteRepactItem(pushArr);
      });
      this.pointRepeatMaps = pointRepeatMaps;
      this.idRepeatMaps = idRepeatMaps;
      setTimeout(() => {
        this.isShowDialog = true;
        this.$forceUpdate();
      }, 800);
    },
    movestart() {
      console.log("movestart");
    },
    async confirmAddrClick(item) {
      let id = item.id;
      let ids = this.points
        .filter((it2) => it2.addr === item.addr)
        .map((item) => item.id);
      const res = await this.axios.post(this.apis.addressDataSureAddress, {
        id: ids,
      });
      console.log(ids, "ids");
      if (res.retCode === 2000) {
        this.$message.success("确认成功!");
        this.isShowDialogFunc();
        this.$store.state.currentTargetAddrInfo = null;
        const totalNum = await this.$children[1].getList();
        if (totalNum > 0) {
          // 第二个参数代表是父页面让他点击的
          this.$children[1].clickclItem(null, true);
        } else {
          this.points = [];
        }

        await addOperationLog({
          title: "确认目标地址",
          content: {
            id,
            obj_number: "目标地址id",
            obj_name: "已确认目标地址",
            old_target_address: id, //此处字符串
            new_target_address: item.addr,
          },
        });
      } else {
        this.$message.warning(res.retMessage);
      }
    },
    async confirmAddrClick2(item) {
      console.log(item, "item");
      // this.$confirm('确认要选择此地址吗？', '提示').then(async ()=>{
      let id = item.id;
      const res = await this.axios.post(this.apis.addressDataSureAddress, {
        id: [Number(id)],
      });
      // console.log('xxx', res);
      if (res.retCode === 2000) {
        this.$message.success("确认成功!");
        // console.log(this.$children[1], 'this.$children');
        // this.$children[1].clickclItem({id: this.$store.state.currentTargetAddrInfo.id})

        // let fIndex = this.pointRepeatMaps[this.currentPoint.id].findIndex(item => item.id == id)
        // if (fIndex != -1) {
        //   this.pointRepeatMaps[this.currentPoint.id].splice(fIndex, 1);
        // console.log(this.pointRepeatMaps[this.currentPoint.id], 'this.pointRepeatMaps[this.currentPoint.id]');
        //   this.$forceUpdate()

        // }
        // this.isShowDialog = false
        await addOperationLog({
          title: "确认目标地址",
          content: {
            id,
            obj_number: "目标地址id",
            obj_name: "已确认目标地址",
            old_target_address: id, //此处字符串
            new_target_address: item.addr,
          },
        });
      } else {
        this.$message.warning(res.retMessage);
      }
      // }).catch(()=>{return})
    },
  },
};
</script>

<style lang="less">
.addressCheck {
  height: 100%;
  min-width: 800px;
  .amap-icon {
    img {
      width: 30px;
      height: auto;
    }
  }
  .amap-overlay-text-container {
    color: #fff;
    background-color: transparent;
    border: none;
  }
}
.isLoagin-address {
  display: flex;
  flex-direction: column;
  /* justify-content: center; */
  align-items: center;
  height: 100%;
  transform: translateY(150px);
}
.isLoagin-address img {
  width: 30px;
  height: 30px;
}
.loading-text1 {
  font-size: 14px;
  /* font-family: PingFangSC-Medium, PingFang SC; */
  font-weight: 600;
  color: #333333;
  line-height: 22px;
  /* margin-top: 10px; */
}
.loading-text2 {
  font-size: 12px;
  /* font-family: PingFangSC-Regular, PingFang SC; */
  font-weight: 400;
  color: #666666;
  line-height: 24px;
}

.address-check_container {
  width: 100%;
  height: 100%;
  position: relative;
  .map {
    width: 100%;
    height: 100%;
  }
}

.posidiv {
  position: fixed;
  z-index: 1000;
  // width: 320px;
  background: #ffffff;
  box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.22);
  border-radius: 4px;
  border: 1px solid #e4e6eb;
  padding: 15px;
  .bzdz {
    position: relative;
    font-size: 14px;
    color: #333333;
    .closeicon {
      position: absolute;
      right: -4px;
      top: -4px;
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
    .b_title {
      font-weight: 600;
    }
    .b_text {
    }
  }

  .p_title {
    line-height: 20px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .p_title img {
    width: 14px;
    height: 14px;
    cursor: pointer;
  }
  .p_list {
    margin-top: 30px;

    .p_item {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin-top: 10px;
      .p_left {
        position: relative;
        width: 25px;
        height: 25px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 15px;
        img {
          position: absolute;
          top: 0;
          left: 0;
          z-index: 101;
          width: 100%;
          height: 100%;
        }
        div {
          z-index: 102;
          color: #fff;
          font-size: 12px;
        }
      }
      .p_right {
        flex: 1;
        .p_name {
          font-size: 14px;
          font-weight: 400;
          color: #333333;
          line-height: 20px;
        }
        .p_lg {
          font-size: 12px;
          font-weight: 400;
          color: #999999;
          line-height: 17px;
          margin: 3px 0;
        }
      }
    }
  }
}

.parentdiv_cls {
  padding: 20px 20px 10px 20px;
}
.choose_btn_cls {
  background-color: #409eff;
  border: none;
  color: #fff;
  padding: 5px 15px;
  border-radius: 4px;
  margin-top: 10px;
  cursor: pointer;
}
.messageBox {
  z-index: 3000 !important;
}

.p_wrapper {
  max-height: 400px;
  overflow: scroll;
}
.p_wrapper::-webkit-scrollbar {
  display: none;
}
</style>